package user

import (
	"context"

	"gorm.io/gorm"
)

type User struct {
	ID        uint64 `db:"id" gorm:"primaryKey;autoIncrement;comment:用户 id"`
	UPassword string `db:"u_password" gorm:"type:varchar(255);not null;default:'';comment:用户密码"`
	UName     string `db:"u_name" gorm:"type:varchar(255);default:'';comment:用户名"`
	UEmail    string `db:"u_email" gorm:"type:varchar(255);default:'';comment:用户 email;uniqueIndex"`
	CreatedAt int64  `db:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt int64  `db:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
}

func (User) TableName() string {
	return "user"
}

type UserModel struct {
	db *gorm.DB
}

type UserModelInterface interface {
	Delete(ctx context.Context, uId uint64) error
	FindOne(ctx context.Context, uId uint64) (*User, error)
	Insert(ctx context.Context, data *User) error
	Update(ctx context.Context, data *User) error
	FindOneByEmail(email string) (*User, error)
}

func NewUserModel(db *gorm.DB) *UserModel {
	return &UserModel{
		db: db,
	}
}

func (m *UserModel) Delete(ctx context.Context, uId uint64) error {
	return m.db.Where("id = ?", uId).Delete(&User{}).Error
}

func (m *UserModel) FindOne(ctx context.Context, uId uint64) (*User, error) {
	var user User
	err := m.db.Where("id = ?", uId).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func (m *UserModel) Insert(ctx context.Context, data *User) error {
	return m.db.Create(data).Error
}

func (m *UserModel) Update(ctx context.Context, data *User) error {
	return m.db.Save(data).Error
}

func (m *UserModel) FindOneByEmail(email string) (*User, error) {
	var user User
	err := m.db.Where("u_email = ?", email).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
